package com.smiier.skin;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OAlert;
import cn.o.app.ui.OAlert.OAlertListener;
import cn.skinapp.R;

import com.evan.common.adapter.BaseListAdapter;
import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.net.TempleAnswerDelTask;
import com.smiier.skin.net.TempleAnswerDelTask.TempleAnswerDelRequest;
import com.smiier.skin.net.TempleAnswerDelTask.TempleAnswerDelResponse;
import com.smiier.skin.net.TempleAnswerGetListTask;
import com.smiier.skin.net.TempleAnswerGetListTask.TempleAnswerGetListRequest;
import com.smiier.skin.net.TempleAnswerGetListTask.TempleAnswerGetListResponse;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.util.StringArrayUtil;
import com.smiier.skin.utils.CommonUtility;
import com.smiier.skin.vo.TwoBeanVo;
import com.umeng.analytics.MobclickAgent;

/**
 * @{# ChooseTemplateActivity.java Create on 2014年10月28日 下午9:14:34
 * 
 * @author <a href="mailto:evan0502@qq.com">Evan</a>
 * @version 1.0
 * @description
 * 
 */
@SuppressWarnings("unused")
public class ChooseTemplateActivity extends BasicActivity implements
		OnRefreshListener<ListView>, OnItemClickListener,
		OnItemLongClickListener {

	private PullToRefreshListView mTemplateList;

	private TextView mTextEmpty;

	private String startID;

	private TemplateAdapter adapter;

	ArrayList<Object> array = new ArrayList<Object>();

	private int checkboxVisiable;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_doctor_answer_template);

		mTemplateList = (PullToRefreshListView) findViewById(R.id.list_template);
		mTextEmpty = (TextView) findViewById(R.id.text_empty);

		checkboxVisiable = getIntent().getIntExtra(Constant.IDENTITY_KEY,
				View.GONE);

		init();
		setNavTitle("解答模板");

		if (checkboxVisiable == View.VISIBLE) {
			setNavRightBtn("确定");
		} else if (checkboxVisiable == View.GONE) {
			setNavRightBtn("创建");
		}

		mTemplateList.setPullRefreshEnabled(true);
		mTemplateList.setScrollLoadEnabled(true);
		mTemplateList.setOnRefreshListener(this);

		mTemplateList.setOnItemClickListener(this);
		mTemplateList.getRefreshableView().setOnItemLongClickListener(this);

		mTemplateList.doPullRefreshing(true);

		// 注册广播，用于创建或者修改模板后通知刷新
		LocalBroadcastManager.getInstance(this).registerReceiver(
				new BroadcastReceiver() {

					@Override
					public void onReceive(Context context, Intent intent) {
						mTemplateList.doPullRefreshing(true);
					}
				}, new IntentFilter(Constant.RECEIVER_CREATE_TEMPLATE));
	}

	private void loadData() {
		TempleAnswerGetListRequest req = new TempleAnswerGetListRequest();
		req.token = GlobalSettings.sToken;
		req.pageSize = 10;
		req.startID = startID;
		TempleAnswerGetListTask task = new TempleAnswerGetListTask();
		task.setRequest(req);
		task.addListener(new NetTaskListener<TempleAnswerGetListTask.TempleAnswerGetListRequest, TempleAnswerGetListTask.TempleAnswerGetListResponse>() {

			@Override
			public void onException(
					INetTask<TempleAnswerGetListRequest, TempleAnswerGetListResponse> task,
					Exception e) {
				mTemplateList.doComplete();
			}

			@Override
			public void onComplete(
					INetTask<TempleAnswerGetListRequest, TempleAnswerGetListResponse> task,
					TempleAnswerGetListResponse response) {
				mTemplateList.doComplete();
				if (response.ResultCode != 200) {
					mTemplateList.setContextEmptyType(true, 2);
					return;
				}
				try {
					JSONArray arr = new JSONArray(JsonUtil
							.convert(response.Res.List));

					if ("0".equals(startID)) {
						array.clear();
					}
					
					
					Log.i("testerror", "解答模板：" + arr.length());
					
					

					if (arr.length() > 0) {
						CommonUtility.putAll(array, arr, true);
						mTemplateList.setHasMoreData(true);
					} else {
						mTemplateList.setHasMoreData(false);
						mTemplateList.getLoadingLayout().setHintText(null);
					}

					if (array.size() > 0) {
						startID = ((JSONObject) array.get(array.size() - 1))
								.getString("Taid");
					} else {
						mTemplateList.getLoadingLayout().setHintText("暂无模板记录");
					}
					if (CommonUtility.isNull(adapter)) {
						adapter = new TemplateAdapter((Activity) getContext(),
								array, checkboxVisiable);
						mTemplateList.setAdapter(adapter);
					} else {
						adapter.notifyUpdate();
					}
					if (array.size() < 1) {
						mTemplateList.setContextEmptyType(true, 2);
					} else {
						mTemplateList.setContextEmptyType(false, 2);
					}
				} catch (Exception e) {
					mTemplateList.setContextEmptyType(true, 2);
					e.printStackTrace();
				}
			}
		});
		add(task);
	}

	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.btn_left) {
			finish();
		} else if (id == R.id.text_right) {
			if (checkboxVisiable == View.VISIBLE) {
				if (!CommonUtility.isNull(values) && values.size() > 0) {
					for (Object object : values.values()) {
						Intent data = new Intent();
						data.putExtra(Constant.IDENTITY_KEY, object.toString());
						setResult(Constant.ACTIVITY_CHOOSE_TEMPLATE, data);
						finish();
						break;
					}
				} else {
					CommonUtility.tip(this, "请选择解答模板");
				}
			} else if (checkboxVisiable == View.GONE) {
				startActivity(new Intent(this,
						CreateZhiliaofanganActivity.class));
			}
		}
	}

	private CheckBox preCheckBox;
	private HashMap<String, Object> values;

	// 根据checkboxVisiable的状态来区别当前界面是选择模板还是模板管理
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (checkboxVisiable == View.VISIBLE) {
			if (CommonUtility.isNull(values)) {
				values = new HashMap<String, Object>();
			}
			CheckBox checkBox = (CheckBox) view.getTag();
			JSONObject object = (JSONObject) checkBox.getTag();
			if (!CommonUtility.isNull(checkBox)) {
				boolean isCheck = checkBox.isChecked();
				checkBox.setChecked(!isCheck);
				if (!isCheck) {
					values.put(object.toString(), object);
				} else {
					values.remove(object.toString());
				}
			}
			if (!CommonUtility.isNull(preCheckBox) && preCheckBox != checkBox) {
				preCheckBox.setChecked(false);
				values.remove(preCheckBox.getTag().toString());
			}
			preCheckBox = checkBox;
		} else {
			try {
				JSONObject object = (JSONObject) view.getTag(R.id.tag_obj);

				String bingzhengGaishu = object.getString("Malady");
				String yongyao = "", yizhu = "";
				JSONArray treatments = object.getJSONArray("Treatments");
				JSONObject obj = null;
				if (treatments.length() > 0) {
					obj = treatments.getJSONObject(0);
					yongyao = obj.getString("Drug");
					yizhu = obj.getString("Advice");
				}
				String questionCategory = CommonUtility
						.convertJSONArray2String(
								object.getJSONArray("Symptom"), "");
				String bingZhengTuiDuan = object.getString("Disease_Inference");
				String[] datas = { bingzhengGaishu, yongyao, yizhu,
						questionCategory, bingZhengTuiDuan };

				Intent intent = new Intent(this,
						CreateZhiliaofanganActivity.class);

				// 获取新增措施数据
				if (treatments.length() > 1) {
					int cuoshiSize = treatments.length();
					String[][] cuoshiDatas = new String[cuoshiSize - 1][];
					for (int i = 1; i < cuoshiSize; i++) {
						obj = treatments.getJSONObject(i);
						cuoshiDatas[i - 1] = new String[] {
								obj.getString("Drug"), obj.getString("Advice") };
					}
					TwoBeanVo vo = new TwoBeanVo();
					vo.datas = cuoshiDatas;
					intent.putExtra(Constant.IDENTITY_KEY_1, vo);
				}

				intent.putExtra(Constant.IDENTITY_KEY, datas);
				intent.putExtra(Constant.IDENTITY_KEY_ID,
						object.getString("Taid"));
				intent.putExtra(Constant.IDENTITY_KEY_TITLE,
						object.getString("Title"));
				startActivity(intent);
			} catch (Exception e) {
			}
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, final View view,
			final int position, long id) {
		OAlert alert = new OAlert(getContext());
		alert.setOK("确认");
		alert.setCancel("取消");
		alert.setTitle("确认删除当前模板吗？");
		alert.show();
		alert.setListener(new OAlertListener() {

			@Override
			public boolean onOK(OAlert alert) {
				JSONObject object = (JSONObject) view.getTag(R.id.tag_obj);
				TempleAnswerDelRequest req = new TempleAnswerDelRequest();
				req.token = GlobalSettings.sToken;
				try {
					req.taids = (ArrayList<Long>) StringArrayUtil
							.parseLong(object.getString("Taid"));
					TempleAnswerDelTask task = new TempleAnswerDelTask();
					task.setRequest(req);
					task.addListener(new NetTaskListener<TempleAnswerDelTask.TempleAnswerDelRequest, TempleAnswerDelTask.TempleAnswerDelResponse>() {

						@Override
						public void onException(
								INetTask<TempleAnswerDelRequest, TempleAnswerDelResponse> task,
								Exception e) {

						}

						@Override
						public void onComplete(
								INetTask<TempleAnswerDelRequest, TempleAnswerDelResponse> task,
								TempleAnswerDelResponse response) {
							if (response.ResultCode != 200) {
								return;
							}
							if (response.Res == GlobalSettings.IS_TRUE) {
								adapter.removeIndex(position);
							} else {
								CommonUtility.tip(getContext(), "删除失败");
							}
						}
					});
					add(task);
				} catch (Exception e) {

				}
				return false;
			}

			@Override
			public boolean onCancel(OAlert alert) {
				return false;
			}
		});

		return true;
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		startID = "0";
		loadData();
	}

	@Override
	public void onPullUpToLoadMore(PullToRefreshBase<ListView> refreshView) {
		loadData();
	}

	@SuppressLint({ "ViewHolder", "InflateParams" })
	public static class TemplateAdapter extends BaseListAdapter {

		// 是否显示checkbox，用于选择和浏览区分
		private int checkboxVisiable;

		/**
		 * @param activity
		 * @param list
		 */
		public TemplateAdapter(Activity activity, ArrayList<?> list) {
			super(activity, list);
		}

		public TemplateAdapter(Activity activity, ArrayList<?> list,
				int checkboxVisiable) {
			super(activity, list);
			this.checkboxVisiable = checkboxVisiable;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = inflater.inflate(R.layout.item_template, null);
			TextView textTemplateName = (TextView) convertView
					.findViewById(R.id.text_template_name);
			TextView textCategory_name = (TextView) convertView
					.findViewById(R.id.text_category_name);
			TextView textChuliYijian = (TextView) convertView
					.findViewById(R.id.text_chuli_yijian);
			LinearLayout llCheckbox = (LinearLayout) convertView
					.findViewById(R.id.ll_checkbox);
			CheckBox checkBox = (CheckBox) convertView
					.findViewById(R.id.check_common);
			try {
				JSONObject template = (JSONObject) getItem(position);

				checkBox.setTag(template);
				convertView.setTag(checkBox);
				convertView.setTag(R.id.tag_obj, template);

				textTemplateName.setText(template.getString("Title"));
				textCategory_name.setText(CommonUtility
						.convertJSONArray2String(
								template.getJSONArray("Symptom"), ""));
				textChuliYijian.setText(template.getString("Malady"));
				llCheckbox.setVisibility(checkboxVisiable);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

	}
	
	
	/*@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(getContext());
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(getContext());
	}*/
}
